package com.example.administrator.liveapp.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.activity.ActionActivity;
import com.example.administrator.liveapp.activity.AdvertisingWebView;
import com.example.administrator.liveapp.activity.ArticleActivity;
import com.example.administrator.liveapp.activity.ArticleDetailsPage;
import com.example.administrator.liveapp.activity.BookingDetailsPage;
import com.example.administrator.liveapp.activity.LiveDetailsPage;
import com.example.administrator.liveapp.activity.MallDetailsPage;
import com.example.administrator.liveapp.activity.SearchActivity;
import com.example.administrator.liveapp.base.BaseFragment;
import com.example.administrator.liveapp.base.BaseRVAdapter;
import com.example.administrator.liveapp.base.BaseViewHolder;
import com.example.administrator.liveapp.bean.MainFragmentBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.GlideImageLoader;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.example.administrator.liveapp.view.MyScrollView;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * 发现Fragment
 */

public class MainFragment extends BaseFragment implements View.OnClickListener {
    private Banner banner;
    private RecyclerView action, zhi_play, book;
    private String[] cateid;//区分轮播图跳转页面
    private String[] id;//轮播图对应的跳转页面id
    private List<String> images;
    private MyScrollView scroll;
    private MainFragmentBean bean;
    private View loadView;//loding页面（加载页）

    /**
     * 下拉刷新
     */
    private RefreshLayout mRefreshLayout;
    private static boolean isFirstEnter = true;

    @Override
    protected View initView() {
        View view = View.inflate(mContext, R.layout.main_fragment, null);
        //

        Typeface xianxia_iconfont = Typeface.createFromAsset(getActivity().getAssets(), "xianxia/iconfont.ttf");
        TextView xianxia = (TextView) view.findViewById(R.id.xianxia);
        xianxia.setTypeface(xianxia_iconfont);

        Typeface remen_iconfont = Typeface.createFromAsset(getActivity().getAssets(), "remen/iconfont.ttf");
        TextView remen = (TextView) view.findViewById(R.id.remen);
        remen.setTypeface(remen_iconfont);

        Typeface wenti_iconfont = Typeface.createFromAsset(getActivity().getAssets(), "wenti/iconfont.ttf");
        TextView wenti = (TextView) view.findViewById(R.id.wenti);
        wenti.setTypeface(wenti_iconfont);

        Typeface qianyue_iconfont = Typeface.createFromAsset(getActivity().getAssets(), "qianyue/iconfont.ttf");
        TextView qianyue = (TextView) view.findViewById(R.id.qianyue);
        qianyue.setTypeface(qianyue_iconfont);

        loadView = view.findViewById(R.id.loadView);
        loadView.setVisibility(View.VISIBLE);
        banner = (Banner) view.findViewById(R.id.banner);
        action = (RecyclerView) view.findViewById(R.id.action);
        zhi_play = (RecyclerView) view.findViewById(R.id.zhi_play);
        book = (RecyclerView) view.findViewById(R.id.book);
        scroll = (MyScrollView) view.findViewById(R.id.scroll);
        scroll.scrollTo(0, 0);
        view.findViewById(R.id.click1).setOnClickListener(this);
        view.findViewById(R.id.click2).setOnClickListener(this);
        view.findViewById(R.id.click3).setOnClickListener(this);
        view.findViewById(R.id.click4).setOnClickListener(this);
        view.findViewById(R.id.search).setOnClickListener(this);
        /**
         * 下拉刷新
         */
        mRefreshLayout = (RefreshLayout) view.findViewById(R.id.refreshLayout);
        setThemeColor(R.color.colorPrimary);
        return view;
    }

    private void setThemeColor(int colorPrimary) {
        mRefreshLayout.setPrimaryColorsId(colorPrimary, android.R.color.holo_blue_dark);
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        scroll.scrollTo(0, 0);
    }

//    @Override
//    public void onPause() {
//        super.onPause();
//        initData();
//    }

    @Override
    protected void initData() {
        String url = AppUrl.URL + AppUrl.HomePageURL;
        XUtils.Get(url, null, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("result", result + "");
                Gson gson = new Gson();
                bean = gson.fromJson(result, MainFragmentBean.class);
                cateid = new String[bean.getBanner().size()];
                id = new String[bean.getBanner().size()];
                images = new ArrayList<>();
                if (bean.getBanner() != null) {
                    for (int i = 0; i < bean.getBanner().size(); i++) {
                        //ViewPager数据源
                        String imageUrl = (bean.getBanner().get(i).getImgurl());
                        cateid[i] = bean.getBanner().get(i).getCateid();
                        id[i] = bean.getBanner().get(i).getTypeid();
                        images.add(AppUrl.URL + imageUrl.substring(0, imageUrl.indexOf("|")));
                    }
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e("----", ex.getMessage() + "");
            }

            @Override
            public void onFinished() {
                super.onFinished();
                mRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
                    @Override
                    public void onLoadmore(RefreshLayout refreshlayout) {
                        //底部加载
                        refreshlayout.finishLoadmore(2000);
                    }

                    @Override
                    public void onRefresh(final RefreshLayout refreshlayout) {
                        //下拉刷新
                        refreshlayout.getLayout().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                initData();
                                refreshlayout.finishRefresh();
                            }
                        }, 2000);
                    }
                });
                banner.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getActivity().getWindowManager().getDefaultDisplay().getWidth() / 16 * 9));

                banner();

                action.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

                book.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));

                zhi_play.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));


                action.setAdapter(new BaseRVAdapter(mContext, bean.getActivity()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_main_action;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position) {
                        if(bean.getActivity().get(position).getActivityimgurl()!=null){
                            Glide.with(mContext)
                                    .load(AppUrl.URL + (bean.getActivity().get(position).getActivityimgurl()).substring(0, (bean.getActivity().get(position).getActivityimgurl()).indexOf("|")))
                                    .into(holder.getImageView(R.id.activity_image));
                        }
                        holder.getTextView(R.id.activity_title).setText(bean.getActivity().get(position).getActivitytitle());
                        holder.getTextView(R.id.activity_name).setText(bean.getActivity().get(position).getActivityauthor());
                        if (bean.getActivity().get(position).getActarea().equals("")) {
                            holder.getTextView(R.id.activity_address).setVisibility(View.GONE);
                        } else {
                            holder.getTextView(R.id.activity_address).setVisibility(View.VISIBLE);
                            holder.getTextView(R.id.activity_address).setText(bean.getActivity().get(position).getActarea());
                        }
                        holder.getTextView(R.id.activity_view).setText(bean.getActivity().get(position).getActivityviewcount());
                        holder.getTextView(R.id.activity_place).setText(bean.getActivity().get(position).getActivityprice());
                        if (!bean.getActivity().get(position).getNowPrice().equals("0.00")&&!bean.getActivity().get(position).getNowPrice().equals("0")) {
                            holder.getTextView(R.id.now_price).setText("¥ " + bean.getActivity().get(position).getNowPrice() + "");
                            holder.getTextView(R.id.now_price).setTextColor(Color.parseColor("#999999"));
                        } else {
                            holder.getTextView(R.id.now_price).setText("免费");
                            holder.getTextView(R.id.now_price).setTextColor(Color.parseColor("#999999"));
                        }
                        addItemClickListener(new OnItemClickListener() {
                            @Override
                            public void itemSelect(int position) {
                                Intent intent = new Intent(mContext, BookingDetailsPage.class);
                                intent.putExtra("activityId", bean.getActivity().get(position).getActivityid());
                                startActivity(intent);
                                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                            }
                        });
                    }

                });

                zhi_play.setAdapter(new BaseRVAdapter(mContext, bean.getVideo()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_main_zhi_play;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position) {
                        Glide.with(mContext)
                                .load(AppUrl.URL + (bean.getVideo().get(position).getVideoimgurl()).substring(1, (bean.getVideo().get(position).getVideoimgurl()).indexOf("|")))
                                .into(holder.getImageView(R.id.video_image));
                        holder.getTextView(R.id.video_title).setText(bean.getVideo().get(position).getVideotitle());
                        holder.getTextView(R.id.video_name).setText(bean.getVideo().get(position).getVideoauthor());
                        addItemClickListener(new OnItemClickListener() {
                            @Override
                            public void itemSelect(int position) {
                                Intent intent = new Intent(mContext, LiveDetailsPage.class);
                                intent.putExtra("videoId", bean.getVideo().get(position).getVideoid());
                                startActivity(intent);
                                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                            }
                        });
                    }


                });

                book.setAdapter(new BaseRVAdapter(mContext, bean.getArticle()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_main_book;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position) {
                        if(bean.getArticle().get(position).getConsumerphoto()!=null&&!bean.getArticle().get(position).getConsumerphoto().equals("")){
                            String str = bean.getArticle().get(position).getConsumerphoto();
                            String photo = str.substring(0,4);
                            if(photo.equals("http")){
                                Glide.with(mContext)
                                        .load(bean.getArticle().get(position).getConsumerphoto())
                                        .into(holder.getImageView(R.id.article_image));
                            }else{
                                Glide.with(mContext)
                                        .load(AppUrl.URL + bean.getArticle().get(position).getConsumerphoto())
                                        .into(holder.getImageView(R.id.article_image));
                            }
                        }
                        if (bean.getArticle().get(position).getIf_record().equals("1")&&bean.getArticle().get(position).getIs_reward().equals("1")) {
                            holder.getImageView(R.id.has_money).setVisibility(View.VISIBLE);
                        } else {
                            holder.getImageView(R.id.has_money).setVisibility(View.GONE);
                        }
                        holder.getTextView(R.id.article_title).setText(bean.getArticle().get(position).getArticletitle());
                        holder.getTextView(R.id.article_name).setText(bean.getArticle().get(position).getConsumername());
                        if (bean.getArticle().get(position).getArticlecolumn().equals("")) {
                            holder.getTextView(R.id.article_column).setVisibility(View.GONE);
                        } else {
                            holder.getTextView(R.id.article_column).setVisibility(View.VISIBLE);
                            holder.getTextView(R.id.article_column).setText(bean.getArticle().get(position).getArticlecolumn());
                        }
                        holder.getTextView(R.id.article_best).setText(bean.getArticle().get(position).getArticlebestcount());
                        holder.getTextView(R.id.article_view).setText(bean.getArticle().get(position).getArticleviewcount());
                        addItemClickListener(new OnItemClickListener() {
                            @Override
                            public void itemSelect(int position) {
                                Intent intent = new Intent(mContext, ArticleDetailsPage.class);
                                intent.putExtra("articleId", bean.getArticle().get(position).getArticleid());
                                startActivity(intent);
                                getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                            }
                        });
                    }


                });
                loadView.setVisibility(View.GONE);
            }
        });

        scroll.scrollTo(0, 0);
        super.initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.search:
                SearchActivity.startAction(getActivity());
                break;
            case R.id.click1:
                startActivity(new Intent(getContext(), ActionActivity.class));
                break;
            case R.id.click2:
                startActivity(new Intent(getContext(), ArticleActivity.class));
                break;
            case R.id.click3:
                Toast.makeText(mContext, "开发中敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.click4:
                Toast.makeText(mContext, "开发中敬请期待 ", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    /**
     * 顶部ViewPager样式设置
     */

    public void banner() {
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        //解决banner(ViewPage)和swipeRefreshLayout(下拉刷新的冲突事件)
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                enableDisableSwipeRefresh(state == ViewPager.SCROLL_STATE_IDLE);
            }

        });
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Intent intent = new Intent();
                switch (position) {
                    case 0:
                        intent.putExtra("link", bean.getBanner().get(0).getLink());
                        intent.putExtra("title",bean.getBanner().get(0).getBannertitle());
                        intent.putExtra("image",bean.getBanner().get(0).getImgurl());
                        intent.putExtra("describe",bean.getBanner().get(0).getDescribe());
                        intent.setClass(mContext, AdvertisingWebView.class);
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 1:
                        intent.putExtra("link", bean.getBanner().get(1).getLink());
                        intent.putExtra("title",bean.getBanner().get(1).getBannertitle());
                        intent.putExtra("image",bean.getBanner().get(1).getImgurl());
                        intent.putExtra("describe",bean.getBanner().get(1).getDescribe());
                        intent.setClass(mContext, AdvertisingWebView.class);
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 2:
                        if (cateid[2].equals("1")) {
                            intent.putExtra("videoId", id[2]);
                            intent.setClass(mContext, LiveDetailsPage.class);
                        } else if (cateid[2].equals("2")) {
                            intent.putExtra("activityId", id[2]);
                            intent.setClass(mContext, BookingDetailsPage.class);
                        } else if (cateid[2].equals("3")) {
                            intent.putExtra("bookId", id[2]);
                            intent.putExtra("bookPrice", bean.getBanner().get(2).getBookPrice());
                            intent.putExtra("remainCount",bean.getBanner().get(2).getRemainCount());
                            intent.setClass(mContext, MallDetailsPage.class);
                        } else if (cateid[2].equals("4")) {
                            intent.putExtra("articleId", id[2]);
                            intent.setClass(mContext, ArticleDetailsPage.class);
                        }
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 3:
                        if (cateid[3].equals("1")) {
                            intent.putExtra("videoId", id[3]);
                            intent.setClass(mContext, LiveDetailsPage.class);
                        } else if (cateid[3].equals("2")) {
                            intent.putExtra("activityId", id[3]);
                            intent.setClass(mContext, BookingDetailsPage.class);
                        } else if (cateid[3].equals("3")) {
                            intent.putExtra("bookId", id[3]);
                            intent.putExtra("bookPrice", bean.getBanner().get(3).getBookPrice());
                            intent.putExtra("remainCount",bean.getBanner().get(3).getRemainCount());
                            intent.setClass(mContext, MallDetailsPage.class);
                        } else if (cateid[3].equals("4")) {
                            intent.putExtra("articleId", id[3]);
                            intent.setClass(mContext, ArticleDetailsPage.class);
                        }
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 4:
                        if (cateid[4].equals("1")) {
                            intent.putExtra("videoId", id[4]);
                            intent.setClass(mContext, LiveDetailsPage.class);
                        } else if (cateid[4].equals("2")) {
                            intent.putExtra("activityId", id[4]);
                            intent.setClass(mContext, BookingDetailsPage.class);

                        } else if (cateid[4].equals("3")) {
                            intent.putExtra("bookId", id[4]);
                            intent.putExtra("bookPrice", bean.getBanner().get(4).getBookPrice());
                            intent.putExtra("remainCount",bean.getBanner().get(4).getRemainCount());
                            intent.setClass(mContext, MallDetailsPage.class);
                        } else if (cateid[4].equals("4")) {
                            intent.putExtra("articleId", id[4]);
                            intent.setClass(mContext, ArticleDetailsPage.class);
                        }
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    case 5:
                        if (cateid[5].equals("1")) {
                            intent.putExtra("videoId", id[5]);
                            intent.setClass(mContext, LiveDetailsPage.class);
                        } else if (cateid[5].equals("2")) {
                            intent.putExtra("activityId", id[5]);
                            intent.setClass(mContext, BookingDetailsPage.class);
                        } else if (cateid[5].equals("3")) {
                            intent.putExtra("bookPrice", bean.getBanner().get(5).getBookPrice());
                            intent.putExtra("remainCount",bean.getBanner().get(5).getRemainCount());
                            intent.putExtra("bookId", id[5]);
                            intent.setClass(mContext, MallDetailsPage.class);
                        } else if (cateid[5].equals("4")) {
                            intent.putExtra("articleId", id[5]);
                            intent.setClass(mContext, ArticleDetailsPage.class);
                        }
                        getActivity().startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }


}
